import { format, addDays, addMinutes, differenceInMinutes } from 'date-fns'

export const TIME_UNIT_MINUTES = 5 // 5分钟为一个基本单位
export const HOURS_PER_DAY = 24
export const MINUTES_PER_HOUR = 60
export const PIXELS_PER_HOUR = 60 // 每小时的像素宽度

/**
 * 获取时间范围（从6点到第二天6点）
 */
export function getDayTimeRange(date: Date) {
  const start = new Date(date)
  start.setHours(6, 0, 0, 0)

  const end = new Date(date)
  end.setDate(end.getDate() + 1)
  end.setHours(6, 0, 0, 0)

  return { start, end }
}

/**
 * 获取前后三天的时间范围
 */
export function getThreeDaysRange(centerDate: Date) {
  const startDate = addDays(centerDate, -1)
  const endDate = addDays(centerDate, 2)

  const start = new Date(startDate)
  start.setHours(6, 0, 0, 0)

  const end = new Date(endDate)
  end.setHours(6, 0, 0, 0)

  return { start, end }
}

/**
 * 将时间转换为像素位置
 */
export function timeToPixels(time: Date, startTime: Date): number {
  const minutes = differenceInMinutes(time, startTime)
  return (minutes / MINUTES_PER_HOUR) * PIXELS_PER_HOUR
}

/**
 * 将像素位置转换为时间
 */
export function pixelsToTime(pixels: number, startTime: Date): Date {
  const minutes = (pixels / PIXELS_PER_HOUR) * MINUTES_PER_HOUR
  // 对齐到5分钟刻度
  const roundedMinutes = Math.round(minutes / TIME_UNIT_MINUTES) * TIME_UNIT_MINUTES
  return addMinutes(startTime, roundedMinutes)
}

/**
 * 格式化时间显示
 */
export function formatTime(date: Date): string {
  return format(date, 'HH:mm')
}

/**
 * 格式化时间显示（包含日期）
 */
export function formatDateTime(date: Date): string {
  return format(date, 'MM-dd HH:mm')
}

/**
 * 格式化日期显示
 */
export function formatDate(date: Date): string {
  return format(date, 'yyyy-MM-dd')
}

/**
 * 生成时间刻度线（主刻度：每小时，副刻度：每10分钟）
 */
export function generateTimeMarks(startTime: Date, endTime: Date) {
  const marks: {
    time: Date
    label: string
    position: number
    type: 'major' | 'minor' // major: 整点, minor: 10分钟
  }[] = []
  let current = new Date(startTime)

  while (current <= endTime) {
    const minutes = current.getMinutes()
    const isMajor = minutes === 0

    marks.push({
      time: new Date(current),
      label: isMajor ? formatTime(current) : '', // 只在整点显示时间
      position: timeToPixels(current, startTime),
      type: isMajor ? 'major' : 'minor'
    })
    current = addMinutes(current, 10) // 每10分钟一个刻度
  }

  return marks
}

/**
 * 检查两个时间段是否重叠
 */
export function isTimeOverlap(
  start1: Date,
  end1: Date,
  start2: Date,
  end2: Date
): boolean {
  return start1 < end2 && end1 > start2
}

/**
 * 计算时间段的持续时间（分钟）
 */
export function getDurationMinutes(start: Date, end: Date): number {
  return differenceInMinutes(end, start)
}
